package com.beiding.fastmock.fram;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.beiding.dbrequest.server.Server;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.api.scripting.AbstractJSObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 丁常磊
 * @date 2021/7/20 17:12
 */

public class PluginClient extends HashMap {

    private Server server;
    private String name;
    private String base;

    public PluginClient(Server server, String name, String base) {
        this.server = server;
        this.name = name;
        this.base = base;
    }

    public Object call(String api, Object body) {
        String bs = JSONObject.toJSONString(body, vf);
        Object o = server.request(name, base + api, bs).syncR();
        if (o instanceof byte[]) {
            return JSONObject.parse((byte[]) o);
        }
        return o;
    }

    @Override
    public Object get(Object key) {

        return new AbstractJSObject() {
            @Override
            public Object call(Object thiz, Object... args) {
                if (args.length == 0) {
                    return PluginClient.this.call("/api/" + key, null);
                }
                return PluginClient.this.call("/api/" + key, args);
            }

            @Override
            public boolean isFunction() {
                return true;
            }
        };
    }

    @Override
    public Object put(Object key, Object value) {
        return null;
    }

    private ValueFilter vf = (o, s, vl) -> {
        if (vl instanceof ScriptObjectMirror) {
            ScriptObjectMirror so = (ScriptObjectMirror) vl;
            if (so.isArray()) {
                return so.values();
            }
        }
        return vl;
    };

}
